<template>
    <div>
      <!--    面包屑导航区域-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item><b>班级管理</b></el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/ClassInfo' }">查询班级信息</el-breadcrumb-item>
        <el-breadcrumb-item><span style="color: #545c99">{{this.ClassName}}</span></el-breadcrumb-item>
      </el-breadcrumb>
      <el-card>
        <el-row>
          <el-col :span="11">
            <el-input placeholder="请输入搜索内容" v-model="queryInfo.searchInfo" clearable @clear="getStudentList">
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-button class="new_btn" @click="StuDialogVisible = true">
              <svg class="icon_add" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                <polygon id="路径" fill="#FFFFFF" points="11.34223 8.55450006 11.34223 1.52678484 8.5311359 1.52678484 8.5311359 8.55450006 1.50342068 8.55450006 1.50342068 11.3655941 8.5311359 11.3655941 8.5311359 18.3933093 11.34223 18.3933093 11.34223 11.3655941 18.3699652 11.3655941 18.3699652 8.55450006"></polygon>
              </svg>
              批量添加学生
            </el-button>
          </el-col>
        </el-row>
        <el-table
          v-loading="loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          ref="multipleTable"
          tooltip-effect="dark"
          style="width: 100%"
          :header-cell-style="{color: '#000000E6'}"
          @selection-change="handleSelectionChange"
          :row-key="getRowKeys"
          :expand-row-keys="expands"
          @expand-change="expandChange"
          :default-sort="{ prop: 'username', order: 'descending'}" :data="pagestulist">
          <!--                多选-->
          <el-table-column
            fixed="left"
            type="selection"
            width="30">
          </el-table-column>
          <!--                展开行-->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <p style="color: #969896">
                <span style="color: #545c99">{{scope.row.name}}</span>
                の题目集如下：
              </p>
              <el-table
                height="200"
                v-loading="loading1"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                :default-sort="{ prop: 'username', order: 'ascending'}" :data="Setlist">
                <el-table-column fixed type="index" label="#"></el-table-column>
                <el-table-column align="center" prop="setName" label="题目集名称"></el-table-column>
                <el-table-column align="center" prop="teachName" label="发起人"></el-table-column>
                <el-table-column align="center" prop="startTime" sortable label="开始时间">
                  <template slot-scope="scope">
                    <span style="color: #545c99">
                      <i class="el-icon-time"></i>
                      {{scope.row.startTime}}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="overTime" sortable label="结束时间">
                  <template slot-scope="scope">
                    <span style="color: red">
                      <i class="el-icon-time"></i>{{scope.row.overTime}}
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column fixed type="index" label="#"></el-table-column>
          <el-table-column align="center" prop="username" sortable label="学号"></el-table-column>
          <el-table-column align="center" prop="name" label="姓名"></el-table-column>
        </el-table>
        <!--      分页区域-->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[ 10, 20, 30, 40]"
          :page-size="queryInfo.pagesize"
          hide-on-single-page
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
        <el-row v-if="this.selected[0]" style="margin-top: 30px">
          <el-col :span="4">
            <el-button @click="DelStu" type="danger">删除学生</el-button>
          </el-col>
        </el-row>
      </el-card>
      <!--    批量添加学生用户的对话框-->
      <el-dialog
        title="批量添加学生用户"
        :visible.sync="StuDialogVisible"
        width="50%" @close="StuDialogClosed" class="role-mask">
        <!--      内容主体区-->
        <h4>每行一名学生用户，学号、姓名用空格分开。</h4>
        <el-form :model="StuToForm" status-icon ref="StuToFormRef">
          <el-form-item prop="text">
            <el-input type="textarea" v-model="StuToForm.text" :autosize="{ minRows:6, maxRows: 16}" placeholder="学号1 姓名1
学号2 姓名2
... ...
... ..." required></el-input>
          </el-form-item>
        </el-form>
        <!--      嵌套展现表格-->
        <el-dialog
          width="50%"
          title="批量添加学生用户"
          :visible.sync="innerVisible"
          append-to-body class="role-mask">
          <el-table
            v-loading="loading2"
            element-loading-text="拼命加载中"
            element-loading-spinner="el-icon-loading"
            height="300" :default-sort="{ prop: 'username', order: 'ascending'}" :data="addStuForm">
            <el-table-column fixed type="index" sortable label="序号"></el-table-column>
            <el-table-column align="center" prop="name" label="姓名">
              <template slot-scope="scope">
                <el-tag>{{scope.row.name}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="username" sortable label="学号"></el-table-column>
          </el-table>
          <div style="margin-top:12px"></div>
          <span slot="footer">
            <el-row>
                 <el-col :span="4" :offset="5" >
                    <el-button class="white_btn" @click="clear">取 消</el-button>
                </el-col>
                <el-col :span="4" :offset="5">
                    <el-button class="new_btn" type="primary" @click="addStu">添 加</el-button>
                </el-col>
            </el-row>
        </span>
        </el-dialog>
        <!--              底部按钮区域-->
        <span slot="footer" class="dialog-footer">
        <el-row>
          <el-col :span="4" :offset="5" >
            <el-button class="white_btn" @click="resetStu">重 置</el-button>
          </el-col>
          <el-col :span="4" :offset="5">
            <el-button class="new_btn" @click="addtoTable()">添 加</el-button>
          </el-col>
        </el-row>
      </span>
      </el-dialog>
    </div>
</template>

<script>
  import axios from 'axios'

  export default {
    name: 'StuDetails',
    data() {
      return{
        // 获取班级学生列表的参数对象
        queryInfo: {
          // 模糊搜索
          searchInfo: '',
          // 当前页数
          pagenum: 1,
          pagesize: 10
        },
        Stulist: [],
        total: 0,
        ClassId: '',
        ClassName: '',
        loading: true, //班级学生列表加载
        loading1: true, //学生题目集加载
        Setlist: [],
        //设置row-key只展示一行
        expands: [],
        getRowKeys(row) {//只展开一行放入当前行id
          return row.username
        },
        selected:[], // 选中的数据列表
        // 添加学生到班级
        StuToForm: {
          text: ''
        },
        innerVisible: false,
        // 表格展示
        xuehao: ['暂无数据'],
        addStuForm:{
          username:'',
          name:''
        },
        StuDialogVisible: false,
        loading2:true, // 添加学生列表加载
      }
    },
    created () {
      this.getClassForm()
    },
    methods:{
      getClassForm(){
        var ClassId = this.$route.query.classId
        var ClassName = this.$route.query.name
        this.ClassId = ClassId
        this.ClassName = ClassName
        this.getStudentList()
        console.log(ClassId, ClassName)
      },
      async getStudentList() {
        var id = this.ClassId
        const { data: res } = await this.$http.get('/student/allStudentOfClass/' + id)
        if (res.status !== 200) {
          return this.$message.error(res.msg + '获取班级学生列表失败!')
        }
        this.Stulist = res.data.student
        console.log(res.data)
        if (this.Stulist.length === res.data.student.length){
          this.total = this.Stulist.length
          this.loading = false
        }
      },
      // 监听 pagesize 改变的事件
      handleSizeChange (newSize) {
        this.queryInfo.pagesize = newSize
        this.getStudentList()
      },
      // 监听页码值改变的事件
      handleCurrentChange (newPage) {
        // console.log(newPage)
        this.queryInfo.pagenum = newPage
        this.getStudentList()
      },
      async getSetList(username){
        const { data: res } = await this.$http.get('/student/allTestSet/' + username)
        if (res.status !== 200) {
          return this.$message.error(res.msg + '获取学生题目集失败!')
        }
        this.Setlist = res.data.set
        console.log(this.Setlist)
        if (this.Setlist.length === res.data.set.length){
          this.loading1 = false
        }
      },
      // 展开事件----动态获取内嵌表数据
      expandChange(row, expandedRows) {
        console.log(row)
        var that = this
        if (expandedRows.length) {
          that.expands = []
          if (row) {
            that.expands.push(row.username)// 每次push进去的是每行的ID
            that.getSetList(row.username)
          }
        } else {
          that.expands = []// 默认不展开
        }
      },
      // 选中该行
      handleSelectionChange(val) {
        this.selected = val;
        console.log(val)
      },
      async DelStu () {
        const confirmResult = await this.$confirm('此操作将从该班级永久删除此学生, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).catch(err => err)
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消删除')
        }
        var StuToClass = []
        var arr = this.selected
        var id = this.ClassId
        arr.forEach(function (item) {
          StuToClass.push({ classId: id, stuId: item.username })
        })
        console.log(StuToClass)
        axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
        const { data: res } = await this.$http.delete('/student/deleteFromClass/', {data: StuToClass})
        if (res.status !== 200) {
          return this.$message.error(res.msg + '删除学生失败！')
        }
        this.$message.success('删除学生成功!')
        this.getStudentList()
      },
      // 监听批量添加学生用户对话框的关闭事件
      StuDialogClosed () {
        this.$refs.StuToFormRef.resetFields()
      },
      resetStu () {
        this.$refs.StuToFormRef.resetFields()
      },
      addtoTable () {
        var table = this.StuToForm.text.split('\n')
        var a = []
        var b = []
        var arr = []
        var i = 0
        while (table[i]) {
          a = table[i]
          b = a.split(' ')
          this.xuehao[i] = b[0] + ' ' + b[1]
          i = i + 1
          arr.push({username: b[0],name: b[1]})
          // console.log(b)
        }
        this.addStuForm = arr
        console.log(this.addStuForm)
        if (this.addStuForm.length === arr.length){
          this.loading2 = false
          this.innerVisible = true
        }
      },
      // 点击按钮，批量添加学生用户
      addStu () {
        this.$refs.StuToFormRef.validate(async valid => {
          // console.log(valid)
          if (!valid) return
          // 调用接口进行批量添加学生用户
          axios.defaults.headers['Content-Type'] = 'application/text;charset=utf-8'
          const { data: res } = await this.$http.post('/student/addToClass/' + this.ClassId, this.StuToForm.text)
          if (res.status !== 200) {
            return this.$message.error('批量添加失败！')
          }
          this.$message.success('批量添加成功!')
          console.log(res)
          // 隐藏批量添加学生用户的对话框
          this.StuDialogVisible = false
          this.innerVisible = false
          this.getStudentList()
        })
      },
      // 清空数据
      clear () {
        this.innerVisible = false
        this.xuehao = ['暂无数据']
      }
    },
    computed: {
      pagestulist: function () {
        var search = this.queryInfo.searchInfo
        if (search) {
          return this.Stulist.filter(function (data) {
            return Object.keys(data).some(function (key) {
              return String(data[key]).toLowerCase().indexOf(search) > -1
            })
          })
        }
        return this.Stulist.slice((this.queryInfo.pagenum - 1) * this.queryInfo.pagesize, this.queryInfo.pagenum * this.queryInfo.pagesize)
      }
    }
  }
</script>

<style scoped>
  .new_btn{
    background: #545c64;
    color: white;
    letter-spacing: 2px;
  }
  .new_btn:hover,.new_btn:focus{
    background: #545c99;
    color: ghostwhite;
    letter-spacing: 2px;
  }
  .icon_add{
    width: 26px;
    height: 26px;
    padding-right: 4px;
    vertical-align:middle;
  }
</style>
